import string
import random
from flask import Blueprint, render_template, jsonify, request, redirect, url_for, session
from exts import mail, db
from flask_mail import Message
from models import EmailCaptchaModel, UserModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash, check_password_hash

bp = Blueprint("auth", __name__, url_prefix="/auth")


@bp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                print("邮箱在数据库中不存在！")
                return redirect(url_for("login"))
            if check_password_hash(user.password, password):
                # cookie一般用来存放登录授权的东西
                # flask中的session,是经过加密后存储在cookie中的
                session['user_id'] = user.id
                return redirect('/')
            else:
                print("密码错误！")
                return redirect(url_for("login"))

        else:
            print(form.errors)
            return redirect(url_for("login"))


@bp.route('/logout')
def logout():
    # 清除session
    session.clear()
    return redirect('/')


# GET :从服务获取数据
# POSt ：将客户端的数据提交个服务器
@bp.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "GET":
        return render_template("register.html")
    else:
        # Post 去请求
        # 验证用户提交邮箱和验证是否正确
        # 表单验证：flask-wtf
        form = RegisterForm(request.form)
        if form.validate():
            username = form.username.data
            password = form.password.data
            email = form.email.data
            user = UserModel(email=email, username=username, password=generate_password_hash(password))
            db.session.add(user)
            db.session.commit()
            # log.info(f"用户： {username}  邮箱地址： {password} 已经注册成功")
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            # log.info(f"用户注册验证不通过，即将返回注册页面")
            return redirect(url_for("auth.register"))


@bp.route("/captcha/email")
def get_email_captcha():
    email = request.args.get("email")
    source = string.digits * 4
    captcha = "".join(random.sample(source, 4))
    # I/O耗时操作，一般放在另一个进程去做，比如redis的任务队列，
    message = Message(subject="知了问答注册验证码", recipients=[email], body=f"您的验证码是:{captcha}")
    mail.send(message)
    # 存储验证码的方案：memcached / redis / 数据库存储, 企业一般都是redis
    # 这里采用的是数据库表的方式存储
    email_captcha = EmailCaptchaModel(email=email, captcha=captcha)
    db.session.add(email_captcha)
    db.session.commit()
    return jsonify({"code": 200, "message": "发生验证码成功", "data": []})


@bp.route("/mail/test")
def mail_test():
    message = Message(subject="邮箱测试", recipients=["1364931029@qq.com"], body="这是一条测试邮件")
    mail.send(message)
    return "邮件发送成功"



